package com.atkxp.stustatusmasystem.interceptor;

import com.atkxp.stustatusmasystem.pojo.Student;
import com.atkxp.stustatusmasystem.pojo.Teacher;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author user
 * @declaration
 * @create 2023/6/4-14:32
 */
//@Component
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //校验用户登陆状态
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //Filter过滤器跨域处理
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));        // 响应标头指定 指定可以访问资源的URI路径
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");//响应标头指定响应访问所述资源到时允许的一种或多种方法
        response.setHeader("Access-Control-Max-Age", "3600");                                 //设置 缓存可以生存的最大秒数
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");               //设置  受支持请求标头
        response.setHeader("Access-Control-Allow-Credentials","true");                        // 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露

        Object isStudent = request.getSession().getAttribute("isStudent");
        if(isStudent == null) {
            response.sendRedirect("/error");
            return;
        }
        //这边举个例子，如果满足某个条件则放行
        if((Boolean) isStudent == true) {
            Student user = (Student) request.getSession().getAttribute("user");
            if(user.getRight() == 0) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                response.sendRedirect("/error");
            }
        } else {
            Teacher user = (Teacher) request.getSession().getAttribute("user");
            if(user != null) {
                if(user.getRight() == 0){
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    response.sendRedirect("/error");
                }
            } else {
                response.sendRedirect("/error");
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
